package com.example.avmanagerweb.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.avmanagerweb.Utils.String.StringUtils;
import com.example.avmanagerweb.Utils.String.StringValidator;
import com.example.avmanagerweb.entity.Devicinpt;
import com.example.avmanagerweb.entity.SysDepartment;
import com.example.avmanagerweb.entity.SysDevic;
import com.example.avmanagerweb.entity.SysUserinfo;
import com.example.avmanagerweb.entity.vo.AlterDevicVo;
import com.example.avmanagerweb.entity.vo.DelDevicListVo;
import com.example.avmanagerweb.entity.vo.GetSysDevicVo;
import com.example.avmanagerweb.entity.vo.SysDevicVo;
import com.example.avmanagerweb.redisService.RedisService;
import com.example.avmanagerweb.result.RLIST;
import com.example.avmanagerweb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xg
 * @since 2023-06-29
 */
@RestController
@RequestMapping("/sys-devic")
public class SysDevicController {
    @Autowired
    private SysDevicService sysDevicService;
    @Autowired
    private StaffdepartmentService staffdepartmentService;
    @Autowired
    private DevicinptService devicinptService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysDepartmentService sysDepartmentService;
    @Autowired
    private SysUserinfoService sysUserinfoService;


    //设备的增删改查


    @PostMapping(value = "/addDevic")
    public RLIST addDevic(@RequestBody SysDevicVo sysDevicVo, HttpServletRequest request){

        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }

        if(sysDevicVo == null){
            return RLIST.error().message("参数为空");
        }
        // 数据校验
        if(StringUtils.isEmpty(sysDevicVo.getDvNum())){
            return RLIST.error().message("设备编号为空");
        }
        boolean validAccount = StringValidator.isValidAccount(sysDevicVo.getDvNum());
        if(!validAccount){
            return RLIST.error().message("设备编号异常 持数字和字母 长度6-12");
        }
        if(StringUtils.isEmpty(sysDevicVo.getDvName())){
            return RLIST.error().message("名称为空");
        }
        boolean validStringNanem = StringValidator.isValidStringNanem(sysDevicVo.getDvName());
        if(!validStringNanem){
            return RLIST.error().message("登录名异常 持数字和字母 汉字 长度2-12");
        }
        if(sysDevicVo.getDvDepartmentID() <= 0){
            return RLIST.error().message("部门ID");
        }

        if(!StringUtils.isEmpty(sysDevicVo.getuPhone())) {
            boolean phoneNumber = StringValidator.isValidPhoneNumber(sysDevicVo.getuPhone());
            if(!phoneNumber){
                return RLIST.error().message("手机号码格式异常");
            }
        }


        //查询自己部门2
        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("账号无部门id");
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);
        boolean fla = true;
        for (SysDepartment sysDepartment : departmentList) {
            System.out.println(sysDepartment.toString() +"  循环");
            System.out.println((sysDepartment.getDepid()+ "=="+ sysDevicVo.getDvDepartmentID()) +"  循环");
            if(sysDepartment.getDepid() == sysDevicVo.getDvDepartmentID()){
                fla = false;
                break;
            }
        }
        if(fla){
            return RLIST.error().message("无法跨部门添加");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("dvNum",sysDevicVo.getDvNum());
        int one = sysDevicService.count(wrapper);
        if(one > 0){
            return RLIST.error().message("设备名存在无法添加");
        }


        if(sysDevicVo.isAddUser()){
            QueryWrapper wp = new QueryWrapper();
            wp.eq("uLoginName",sysDevicVo.getDvNum());
            wp.eq("upolno",sysDevicVo.getDvNum());
            int one1 = sysUserinfoService.count(wp);
            if(one1 > 0){
                return RLIST.error().message("设备账号和用户账号创建绑定  用户账号存在相同 无法创建");
            }
        }
        System.out.println(sysDevicVo.toString()+"-----------------------------------------");
        boolean save = sysDevicService.addDevic(sysDevicVo);
        if(save) {
            return RLIST.ok();
        }
        return RLIST.error().message("添加异常");
    }

    @DeleteMapping(value = "/delDevic")
    public RLIST delDevic(@RequestParam("id") int id, HttpServletRequest request){
        if(id<=0){
            return RLIST.error().message("id异常");
        }

        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }

        Devicinpt devicinpt = devicinptService.getById(id);
        if(devicinpt == null){
            return RLIST.error().message("设备不存在");
        }


        {
            //查询自己部门2
            String  json = (String) redisService.getValue(value+"");
            JSONObject jsonObject = JSONObject.parseObject(json);
            SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
            Integer infoid = sysUserinfo.getUdepid();
            if(infoid== null ||infoid <= 0){
                return RLIST.error().message("账号无部门id");
            }
            List<SysDepartment> departmentList = sysDepartmentService.getSubquery(infoid);
            boolean fla = true;
            for (SysDepartment sysDepartment : departmentList) {
                System.out.println(sysDepartment.toString() +"  循环");
                System.out.println((sysDepartment.getDepid()+ "=="+ devicinpt.getDepartmentid()) +"  循环");
                if(sysDepartment.getDepid() == devicinpt.getDepartmentid()){
                    fla = false;
                    break;
                }
            }
            if(fla){
                return RLIST.error().message("无法跨部门删除");
            }
        }



        boolean b = sysDevicService.removeById(id);

        if (true){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }

    }

    @DeleteMapping(value = "/delDevic22")
    public RLIST delDevic22(@RequestParam("id") int id){

        boolean b = sysDevicService.removeById(id);

        if (b){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }

    }


    @DeleteMapping("/delDevicList")
    public RLIST delDevicList(@RequestBody DelDevicListVo delDevicListVo, HttpServletRequest request){
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }
        //查询自己部门2
        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("账号无部门id");
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);

        if(delDevicListVo.getId() == null || delDevicListVo.getId() <= 0) {
            return RLIST.error().message("操作id异常");
        }
        if(sysUserinfo.getUid() != delDevicListVo.getId()) {
            return RLIST.error().message("操作id不匹配");
        }
        if(delDevicListVo.getDelList() == null || delDevicListVo.getDelList().size() <= 0) {
            return RLIST.error().message("删除id异常");
        }
        List<Integer> listByIds = delDevicListVo.getDelList();
        System.out.println(listByIds.toArray());
        if(listByIds == null || listByIds.size() == 0){
            return RLIST.error();
        }
        List<Devicinpt> devicinpts = devicinptService.listByIds(listByIds);
        if(devicinpts == null || devicinpts.size() == 0){
            return RLIST.error().message("批量删除id不存在");
        }
        boolean b = sysDevicService.delDevList(devicinpts, departmentList, delDevicListVo.isDelUser());
        if(b){


            return RLIST.ok();
        } else {
            return RLIST.error();
        }
    }


    @PostMapping(value = "/alterDevic")
    public RLIST alterDevic(@RequestBody AlterDevicVo alterDevicVo, HttpServletRequest request){

        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }
        // 数据校验

        if(alterDevicVo == null){
            return RLIST.error().message("参数为空");
        }
        if(alterDevicVo.getDvid() == null || alterDevicVo.getDvid() <= 0){
            return RLIST.error().message("ID异常 0|null");
        }


        SysDevic sysDevic = new SysDevic();
        Devicinpt byId = devicinptService.getById(alterDevicVo.getDvid());
        if(byId == null){
            return RLIST.error().message("设备不存在");
        }
        sysDevic.setDvid(alterDevicVo.getDvid());          //设备id


        if(!StringUtils.isEmpty(alterDevicVo.getDvName())) {
            boolean validStringNanem = StringValidator.isValidStringNanem(alterDevicVo.getDvName());
            if(!validStringNanem){
                return RLIST.error().message("登录名异常 持数字和字母 汉字 长度2-12");
            }


            sysDevic.setDvname(alterDevicVo.getDvName());        //名称
        }

        System.out.println(alterDevicVo.getDvDepartmentID() +"alterDevicVo.getDvDepartmentID()");
        if(alterDevicVo.getDvDepartmentID() != null) {
            {
                //查询自己部门2
                String  json = (String) redisService.getValue(value+"");
                JSONObject jsonObject = JSONObject.parseObject(json);
                SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
                Integer infoid = sysUserinfo.getUdepid();
                if(infoid== null ||infoid <= 0){
                    return RLIST.error().message("账号无部门id");
                }
                List<SysDepartment> departmentList = sysDepartmentService.getSubquery(infoid);
                boolean fla = true;
                for (SysDepartment sysDepartment : departmentList) {
                    System.out.println(sysDepartment.toString() +"  循环");
                    System.out.println((sysDepartment.getDepid()+ "=="+ alterDevicVo.getDvDepartmentID() )+"  循环");
                    if(sysDepartment.getDepid() == alterDevicVo.getDvDepartmentID()){
                        fla = false;
                        break;
                    }
                }
                if(fla){
                    return RLIST.error().message("无法跨部门修改");
                }
            }


            sysDevic.setDvdepartmentid(alterDevicVo.getDvDepartmentID());     //部门ID


        }



        if(!StringUtils.isEmpty(alterDevicVo.getUphone())) {


            boolean validStringNanem = StringValidator.isValidPhoneNumber(alterDevicVo.getUphone());
            if(!validStringNanem){
                return RLIST.error().message("手机号码格式异常");
            }
            sysDevic.setDvphoneno(alterDevicVo.getUphone());      //手机号 可为空
        }
        if(!StringUtils.isEmpty(alterDevicVo.getDvCarNo())) {
            sysDevic.setDvcarno(alterDevicVo.getDvCarNo());      //车牌号 可为空
        }

        sysDevic.setDvfenceid(alterDevicVo.getDvFenceID());   //围栏id 可为空
        sysDevic.setDvvideoserverid(alterDevicVo.getDvVideoServerID());   //视频服务器id 默认34
        sysDevic.setDvdevtype(alterDevicVo.getDvDevType());   //设备类型 默认2
        sysDevic.setDvobdserverid(alterDevicVo.getDvOBDServerID());   //终端运行服务器id 默认33
        if(!StringUtils.isEmpty(alterDevicVo.getDvIMEI())) {
            sysDevic.setDvimei(alterDevicVo.getDvIMEI());   //IMEI号
        }
        sysDevic.setDvrecordvideo(alterDevicVo.getDvRecordVideo());   //后台是否录像 默认0
        sysDevic.setDvusefence(alterDevicVo.getDvUseFence());   //是否使用围栏 默认0
        sysDevic.setDvoutfencealarm(alterDevicVo.getDvOutFenceAlarm());   //离开围栏报警 默认0

        boolean b = sysDevicService.updateById(sysDevic);
        if(b){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }
    }



    @PostMapping(value = "/getDevic")
    public RLIST getDevic(@RequestBody GetSysDevicVo getSysDevicVo, HttpServletRequest request){
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }

        //校验
        if(getSysDevicVo.getPageNo() <= 0){
            //当前页
            return RLIST.error().message("页数异常");
        }
        if(getSysDevicVo.getPageSize() <= 0){
            //每页条数
            return RLIST.error().message("页条数异常");
        }
        //查询自己部门2
        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("异常 账号无部门id");
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);


        Integer udepid = getSysDevicVo.getGroupId();
        Page<Devicinpt> page = new Page<>(getSysDevicVo.getPageNo(), getSysDevicVo.getPageSize());
        QueryWrapper wrapper = new QueryWrapper();
        if(getSysDevicVo.getId() > 0){
            wrapper.eq("DevicID",getSysDevicVo.getId());
        }
        if(!StringUtils.isEmpty(getSysDevicVo.getDevno())){
            wrapper.eq("DevNo",getSysDevicVo.getDevno());
        }
        if(!StringUtils.isEmpty(getSysDevicVo.getDevname())){
            wrapper.like("DevName",getSysDevicVo.getDevname());
        }
        if(udepid != null && udepid != 0){
            boolean fla = true;
            for (SysDepartment sysDepartment : departmentList) {
                if(sysDepartment.getDepid() == udepid){
                    fla = false;
                    break;
                }
            }
            if(fla){
                return RLIST.error().message("无法跨部门查询");
            }
            wrapper.eq("DepartmentID",udepid);
        }else {

            List<Integer> depIdList = new ArrayList<>();
            if(departmentList == null || departmentList.size()<=0 ){
                return RLIST.error().message("查询子部门结构异常");
            }
            for (SysDepartment sysDepartment : departmentList) {
                depIdList.add(sysDepartment.getDepid());
            }
            wrapper.in("DepartmentID", depIdList);
        }
        Page pageList = devicinptService.page(page, wrapper);
        //总条数
        long total = pageList.getTotal();
        List<Devicinpt> list = pageList.getRecords();
        //页码总数
        long numPage = 0;
        if (total == 0) {
            numPage = 1L;
        } else if (list.size() == 0) {
            numPage = 1L;
        } else {
            numPage = (long) Math.ceil(total / (double) getSysDevicVo.getPageSize());
        }
        return RLIST.ok().data("data", list).data("total", total).data("numPage", numPage);

    }


    @PostMapping("/addLisrDevic")
    public RLIST addLisrDevic(@RequestBody SysDevicVo sysDevicVo, HttpServletRequest request){
        System.out.println(sysDevicVo.isAddUser());
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }
        //校验
        if(sysDevicVo == null){
            return RLIST.error().message("参数为空");
        }
        // 数据校验
        if(StringUtils.isEmpty(sysDevicVo.getDvNum())){
            return RLIST.error().message("设备编号为空");
        }
        boolean validAccount = StringValidator.isValidAccount(sysDevicVo.getDvNum());
        if(!validAccount){
            return RLIST.error().message("设备编号异常 持数字和字母 长度6-12");
        }
        if(StringUtils.isEmpty(sysDevicVo.getDvName())){
            return RLIST.error().message("名称为空");
        }
        boolean validStringNanem = StringValidator.isValidStringNanem(sysDevicVo.getDvName());
        if(!validStringNanem){
            return RLIST.error().message("登录名异常 持数字和字母 汉字 长度2-12");
        }
        if(sysDevicVo.getDvDepartmentID() <= 0){
            return RLIST.error().message("部门ID");
        }

        if(!StringUtils.isEmpty(sysDevicVo.getuPhone())) {
            boolean phoneNumber = StringValidator.isValidPhoneNumber(sysDevicVo.getuPhone());
            if(!phoneNumber){
                return RLIST.error().message("手机号码格式异常");
            }
        }
        if(sysDevicVo.getDevicNumber()<=0){
            return RLIST.error().message("批量添加数异常");
        }

        {
            //查询自己部门2
            String  json = (String) redisService.getValue(value+"");
            JSONObject jsonObject = JSONObject.parseObject(json);
            SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
            Integer infoid = sysUserinfo.getUdepid();
            if(infoid== null ||infoid <= 0){
                return RLIST.error().message("账号无部门id");
            }
            List<SysDepartment> departmentList = sysDepartmentService.getSubquery(infoid);
            boolean fla = true;
            for (SysDepartment sysDepartment : departmentList) {
                System.out.println(sysDepartment.toString() +"  循环");
                System.out.println((sysDepartment.getDepid()+ "=="+ sysDevicVo.getDvDepartmentID() )+"  循环");
                if(sysDepartment.getDepid() == sysDevicVo.getDvDepartmentID()){
                    fla = false;
                    break;
                }
            }
            if(fla){
                return RLIST.error().message("无法跨部门批量添加");
            }
        }



        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("dvNum",sysDevicVo.getDvNum());
        int count = sysDevicService.count(wrapper);
        if(count>0){
            return RLIST.error().message("存在类似的设备编号无法使用该编号批量添加");
        }
        if(sysDevicVo.isAddUser()){
            QueryWrapper wp = new QueryWrapper();
            wp.like("uLoginName",sysDevicVo.getDvNum());
            wp.like("upolno",sysDevicVo.getDvNum());
            int one1 = sysUserinfoService.count(wp);
            if(one1 > 0){
                return RLIST.error().message("设备账号和用户账号创建绑定  用户账号存在相同 无法创建");
            }
        }

        boolean b = sysDevicService.saveDevicLisr(sysDevicVo);
        if(!b){
            return RLIST.error();
        }
        return RLIST.ok();

    }




}

